package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.KnowAnswerAdapter;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.QuestAnswerListData;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.listener.IKnowAnswerAddListener;
import com.wbao.dianniu.listener.IKnowAnswerDelListener;
import com.wbao.dianniu.listener.IKnowAnswerListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.KnowAnswerAddManger;
import com.wbao.dianniu.manager.KnowAnswerDelManger;
import com.wbao.dianniu.manager.KnowAnswerListManger;
import com.wbao.dianniu.update.KnowledgeHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.ReplyHelper;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2017/9/12.
 */

public class KnowAnswerActivity extends AppCompatActivity implements IKnowAnswerListListener, IKnowAnswerAddListener,
        ReplyHelper.ReplyListener, IKnowAnswerDelListener, View.OnClickListener, CommentLongClickHelper.ICommentLongListener {

    private KnowAnswerListManger manager;
    /**
     * 标题左侧的返回按键
     */
    private ImageButton backBtn;
    /**
     * 标题
     */
    private TextView titleTV;

    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private PullToRefreshListView mPullToRefreshView;
    private ListView mListView;
    private Map<Integer, String> replyMap = null;
    private KnowAnswerAddManger addManger;
    private int knowledgeId;
    private KnowAnswerAdapter adapter;
    private List<QuestAnswerListData> mList = new ArrayList<>();
    private Dialog dialog;
    private KnowAnswerDelManger deleteManager;

    private RelativeLayout mInfoRL;
    private EmotionMainFragment emotionMainFragment;
    private EditText bar_edit_text;
    private ImageView bar_image_add_btn;
    private Button bar_btn_send;
    private InputMethodManager mInputManager;//软键盘管理类
    private CommentLongClickHelper commentLongClickHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_know_answer);
        knowledgeId = getIntent().getIntExtra(Const.INTENT_ID, 0);
        initView();
        initData();
        initEmotionMainFragment();
    }

    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment() {
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(mInfoRL, bar_image_add_btn, bar_edit_text);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    private void initView() {
        backBtn = findViewById(R.id.back_button);
        backBtn.setOnClickListener(this);
        titleTV = findViewById(R.id.title);
        titleTV.setText("知识评论");

        mPullToRefreshView = findViewById(R.id.know_answer_listview);
        mPullToRefreshView.setMode(Mode.BOTH);
        mPullToRefreshView.setOnRefreshListener(onRefreshListener);
        mListView = mPullToRefreshView.getRefreshableView();
        registerForContextMenu(mListView);

        adapter = new KnowAnswerAdapter(this);
        adapter.addData(mList);
        mListView.setAdapter(adapter);
//        mListView.setOnItemLongClickListener(onItemLongClick);
        mInfoRL = findViewById(R.id.content_relayout);

        bar_image_add_btn = findViewById(R.id.bar_image_add_btn);
        bar_btn_send = findViewById(R.id.bar_btn_send);
        bar_btn_send.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(KnowAnswerActivity.this, "请输入你的评论!");
                    return;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
            }
        });
        bar_edit_text = findViewById(R.id.bar_edit_text);
        bar_edit_text.setOnClickListener(this);
        bar_edit_text.setOnEditorActionListener(actionListener);
        bar_edit_text.addTextChangedListener(watcher);
        if (!GlobalContext.getPerfectData()) {
            bar_edit_text.setFocusable(false);
            bar_btn_send.setFocusable(false);
            bar_image_add_btn.setVisibility(View.GONE);
        } else {
            bar_edit_text.setFocusable(true);
        }

    }

    private void initData() {
        manager = new KnowAnswerListManger(this);
        manager.addknowAnswerListListener(this);
        requestData(currentPage);
        addManger = KnowAnswerAddManger.getInstance(this);
        addManger.addknowAnswerAddListener(this);
        deleteManager = new KnowAnswerDelManger(this);
        deleteManager.addknowAnswerDelListener(this);
        // 回复@功能监听
        ReplyHelper.getInstance().addReplyListener(this);
        commentLongClickHelper = CommentLongClickHelper.getInstance();
        commentLongClickHelper.addCommentLongClickListener(this);
    }

    PullToRefreshBase.OnRefreshListener2 onRefreshListener2 = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh() {

        }

        @Override
        public void onPullUpToRefresh() {

        }
    };
    PullToRefreshBase.OnRefreshListener onRefreshListener = new PullToRefreshBase.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // 上拉刷新 加载请求数据
            pullUpRequest();
        }
    };

    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }

    // 上拉刷新数据请求
    private void pullUpRequest() {
        // 没有搜索结果 或者数据为空 上拉没有效果
        ++currentPage;
        reqData(currentPage);
    }

    private void reqData(int page) {
        manager.knowAnswerList(GlobalContext.getAccountId(), knowledgeId, page * PAGE_COUNTS, PAGE_COUNTS, 0);
    }

    TextView.OnEditorActionListener actionListener = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_SEND /*||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)*/) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(KnowAnswerActivity.this, "请输入你的评论!");
                    return false;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                Utils.hideSoftInput(KnowAnswerActivity.this, bar_edit_text);
                return true;
            }
            return false;
        }

    };

    private void addAnswerComment(String comment) {
        if (null != replyMap) {
            for (Map.Entry<Integer, String> entry : replyMap.entrySet()) {
                comment = "回复" + entry.getValue() + ":" + comment;
            }
        }
        // 回复之前 增加等待框
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();
        addManger.knowAnswerAdd(GlobalContext.getAccountId(), knowledgeId, comment, JsonUtil.mapToStringJson(replyMap), null, 0, 0);
    }

    private void requestData(int page) {
        manager.knowAnswerList(GlobalContext.getAccountId(), knowledgeId, page * PAGE_COUNTS, PAGE_COUNTS, 0);
    }

    @Override
    public void onKnowAnswerListFailure(int errorCode, String errorMsg) {
        mPullToRefreshView.onRefreshComplete(false, false);
    }

    @Override
    public void onKnowAnswerListSuccess(List<QuestAnswerListData> list) {
        mPullToRefreshView.onRefreshComplete(false, false);
        if (null != list) {
            if (0 != currentPage) {
                adapter.addData(list);
            } else {
                adapter.setData(list);
            }
            mList = adapter.getList();
            adapter.notifyDataSetChanged();
//            if (mList.size() == 0) {
//            } else {
//            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_button:
                finish();
                break;
            /*case R.id.bar_btn_send: // 评论
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(KnowAnswerActivity.this, "请输入你的评论!");
                    return;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
                //Utils.hideSoftInput(KnowAnswerActivity.this, bar_edit_text);
                break;*/

            default:
                break;
        }
    }

    @Override
    public void onKnowAnswerAddFailure(int errorCode, String errorMsg) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onKnowAnswerAddSuccess(QuestAnswerListData obj) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        // 评论完成 添加一条记录到回复列表
        if (null != obj) {
            if (0 != obj.pid) {
                return;
            }

            bar_edit_text.setText("");
            bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
            if (null != replyMap) {
                replyMap.clear();
            }
            adapter.addOneData(obj);
            KnowledgeHelper.getInstance().replyNotify(knowledgeId, mList.size());
            adapter.notifyDataSetChanged();

        }
    }

    @Override
    public void reply(String userName, int userId, int pid) {
        bar_edit_text.setText("");
        bar_edit_text.setHint("回复:" + userName);
        bar_edit_text.requestFocus();
        bar_edit_text.post(new Runnable() {
            @Override
            public void run() {
                mInputManager.showSoftInput(bar_edit_text, 0);
            }
        });
        // add Reply logical
        replyMap = new HashMap<Integer, String>();
        replyMap.put(userId, userName);
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                // 清空输入内容时，清除@效果的hashMap
                bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
                if (null != replyMap) {
                    replyMap.clear();
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReplyHelper.getInstance().removeReplyListener(this);
        if (null != commentLongClickHelper)
            commentLongClickHelper.removeCommentLongClickListener(this);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (null != manager) {
            manager.removeknowAnswerListListener(this);
        }
        if (null != addManger) {
            addManger.removeknowAnswerAddListener(this);
        }
        if (null != deleteManager) {
            deleteManager.removeknowAnswerDelListener(this);
        }
        // 移除绑定的EditText
        if (null != emotionMainFragment) {
            emotionMainFragment.removeEditText();
        }

    }

    @Override
    public void onKnowAnswerDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onKnowAnswerDelSuccess() {

    }

    @Override
    public void commentLongClick(QuestAnswerListData data) {
        deleteManager.knowAnswerDel(GlobalContext.getAccountId(), data.id);
        adapter.deleteById(data.id);
        // 删除后，回复数减一
        KnowledgeHelper.getInstance().replyNotify(knowledgeId, adapter.getList().size());
    }

    float previousX = 0;
    float previousY = 0;
    float softHeight = 0;
    boolean inOutside = true;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                previousX = ev.getRawX();
                previousY = ev.getRawY();
                int[] l = {0, 0};
                bar_image_add_btn.getLocationInWindow(l);
                softHeight = l[1];
                inOutside = ev.getY() < softHeight;
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = previousY - ev.getRawY();
                float dx = previousX - ev.getRawX();
                if ((Math.abs(dy) > 30 || Math.abs(dx) > 30) && inOutside) {
                    hideKeyboard();
                }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        emotionMainFragment.onBackPress();
    }

}
